<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/12
 * Time: 11:07
 */
//namespace weixin\Wx;
echo 111;
class Wx{
    protected  $accessToken;
    protected  $token;
    protected  $appid;
    protected  $secret;
    protected  $ToUserName;
    protected  $FromUserName;
    protected  $MsgType;
    protected  $event;
    protected  $EventKey;
    protected  $Content;
    protected  $CreateTime;
    function __construct($config){
        //判断有下列几个值时时token验证
        $this->token=$config['token'];
        $this->appid=$config['appid'];
        $this->secret=$config['secret'];
        if(isset($_GET['signature'])&& isset($_GET['timestamp'])&&isset($_GET['nonce'])&&isset($_GET['echostr'])){
            $this->valid();
        }else{
            $obj=$this->getInfo();
            $this->ToUserName= $obj->ToUserName;
            $this->FromUserName = $obj->FromUserName;  //用户
            $this->MsgType = $obj->MsgType;//消息类型
            $this->event=$obj->Event;//事件类型
            $this->EventKey = $obj->EventKey;
            $this->Content=$obj->Content;
            $this->CreateTime=time();
           $this->getAcessToken();

        }
    }
    //token验证
    function valid(){
        $signature=$_GET['signature'];
        $timestamp=$_GET['timestamp'];
        $nonce=$_GET['nonce'];
        $echostr=$_GET['echostr'];
        $tmpArr=array($timestamp,$nonce,$this->token);
        sort($tmpArr,SORT_STRING);
        $tmpStr=implode($tmpArr);
        $tmpStr=sha1($tmpStr);
        if($signature==$tmpStr){
            echo $echostr;
            exit;
        }
    }
    //curl获取数据
    function curl($url,$data=[]){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。支持https协议
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        //如果data有数据传入则为POST提交反之为GET
        if($data){
            // 开启post提交数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);//所需传的数组用http_bulid_query()函数处理一下，就ok了
        }
        $output = curl_exec($ch);
        curl_close($ch);
        //返回获得的数据
        return $output;
    }
    //获取access_token，缓存access_token（过期时间为2小时）用框架方法
    function  getAcessToken(){
        $url='https://api.weixin.qq.com/cgi-bin/token';
        $data=array(
            'grant_type'=>'client_credential',
            'appid'=>$this->appid,
            'secret'=>$this->secret,
        );
        //生成缓存文件
        $cacheName=md5($data['appid'].$data['secret']);
        $file=__DIR__.'\cache\\'.$cacheName.'.php';
        if(is_file($file) && filemtime($file)+7100<time()){
            $rs=unserialize(file_get_contents($file));
            echo '这是缓存读取';
        }else{
           $rs= json_decode($this->curl($url,$data),true);
            if(isset($rs['errcode'])){
                return false;
            }
            file_put_contents($file,serialize($rs));
        }

       return $this->accessToken=$rs['access_token'];
    }
    //获取信息
    function getInfo()
    {
        $post = file_get_contents("php://input");//
        //$post = $GLOBALS['HTTP_RAW_POST_DATA'];//有时候这个函数不能获取数据，改用上面的函数获取数据
        if ($post) {
            $obj = simplexml_load_string($post);
            return $obj;
        }
    }
   //文本消息回复
    function textMsg($text){
        $content = "
                <xml>
                <ToUserName><![CDATA[{$this->FromUserName}]]></ToUserName>
                <FromUserName><![CDATA[{$this->ToUserName}]]></FromUserName>
                <CreateTime>{$this->CreateTime}</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[$text]]></Content>
                </xml> ";
        echo $content;
    }
    //语音回复
    function voiceMsg($text){
        $content = "
                <xml>
                <ToUserName><![CDATA[{$this->FromUserName}]]></ToUserName>
                <FromUserName><![CDATA[{$this->ToUserName}]]></FromUserName>
                <CreateTime>{$this->CreateTime}</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[$text]]></Content>
                </xml> ";
        echo $content;
    }
    //被动回复消息
    function Reply()
    {
        if ($this->MsgType == 'text') {
            if ($this->Content == '你好') {
                $this->textmsg('你好');
            } elseif ($this->Content == '电话') {
                $this->textMsg('15008276357');
            } else {
                $this->textMsg('你想获取的信息暂时没有,谢谢你的关注');
            }
        } elseif ($this->MsgType == 'image') {
            $this->textmsg('你发的是图片');
        } elseif ($this->MsgType == 'voice') {
            $this->textmsg('你发的是语音');
        } elseif ($this->MsgType == 'video') {
            $this->textmsg('你发的是视频');
        } elseif ($this->MsgType == 'news') {
            $this->textmsg('你发的是图文');
        } elseif ($this->MsgType == 'music') {
            $this->textmsg('你发的是音乐');
        } elseif (strtolower($this->MsgType) == 'event') {
            if (strtolower($this->event) == 'subscribe') {
                $this->textMsg('欢迎订阅本账号！');
            } elseif (strtolower($this->event) == 'click') {
                switch ($this->EventKey) {
                    case "V1001_TODAY_MUSIC" :  //菜单中key相关值
                        $this->textMsg('https://www.baidu.com');
                        break;
                    case "erweima":
                }
            }
        }
    }
    //主动发消息
    //在返回成功时，意味着群发任务提交成功，并不意味着此时群发已经结束，
    //所以，仍有可能在后续的发送过程中出现异常情况导致用户未收到消息，
    //如消息有时会进行审核、服务器不稳定等。此外，群发任务一般需要较长的时间才能全部发送完毕，请耐心等待。
   //群发接口新增 clientmsgid 参数，开发者调用群发接口时可以主动设置 clientmsgid 参数，避免重复推送
    //如果该 clientmsgid 已经存在一条群发记录，则会拒绝本次群发请求，返回已存在的群发msgid，开发者可以调用“查询群发消息发送状态”接口查看该条群发的状态
    function sendMsg($id,$type='text',$content){
        $url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=".$this->accessToken;
        $arr=array('image','voice','mpnews','mpvideo');
        if($type=='wxcard'){
            $data=array(
                'filter'=>array(
                    'is_to_all'=>false,
                    'tag_id'=>$id
                ),
                'wxcard'=>array(
                    'card_id'=>$content
                ),
                'msgtype'=>'wxcard'
            );
        }else if(in_array($type,$arr)){
            $data=array(
                'filter'=>array(
                    'is_to_all'=>false,
                    'tag_id'=>$id
                ),
                "{$type}"=>array(
                    'media_id'=>$content
                ),
                'msgtype'=>"{$type}",
                "send_ignore_reprint"=>0
            );
        }else{
            $data=array(
                'filter'=>array(
                    'is_to_all'=>false,
                    'tag_id'=>$id
                ),
                'text'=>array(
                    'content'=>urlencode($content)
                ),
                'msgtype'=>'text'
            );
        }

       /* $data='{
               "filter":{
                  "is_to_all":true,
                  "tag_id":110
               },
               "text":{
                  "content":"瓜娃子"
               },
               "msgtype":"text"

              }';*/
        $data=urldecode(json_encode($data));
       $rs= json_decode($this->curl($url,$data),true);
        var_dump($rs);//$rs['msg_id']可以存入数据库，可以做后续查看删除等操作
        if($rs['errcode']==0){
            echo '群发成功';

        }else{
            echo '群发失败';
        }
    }
    //生成二维码
    function getTimeCode(){
        header("content-type:text/html;charset='utf8'");
        $url= "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->accessToken;//数据格式：json
        //"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}
        $postArr=array(
            'expire_seconds'=>604800,//七天临时时间
            'action_name'=>'QR_SCENE',
            'action_info'=>array(
                'scene'=>array('scene_id'=>1500),
            ),
        );
        //echo $this->accessToken;
       //
        $postArr=json_encode($postArr);
        //echo 111;die;
        $rs=json_decode($this->curl($url,$postArr),true);
        $ticket=$rs['ticket'];
        //var_dump($rs);
        $url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".UrlEncode($ticket);
        echo "<img src='".$url."'/>";
    }
    //创建菜单
    function createItem(){
        //创建微信菜单
        //目前微信接口的调用方式都是通过curl post/get
        $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->accessToken;
        $postarr=Array(
            'button'=>array(
                Array(
                    'name'=>urlencode('百度'),
                    'type'=>'view',
                    'url'=>'https://baidu.com',
                ),//第一个一级菜单
                array(
                    'name'=>urlencode('商城'),
                    'sub_button'=>array(
                        Array(
                            'name'=>urlencode('草莓'),
                            'type'=>'view',
                            'url'=>'https://baidu.com',
                        ),//第一个二级菜单
                        Array(
                            'name'=>urlencode('苹果'),
                            'type'=>'view',
                            'url'=>'https://baidu.com',
                        ),//第二个二级菜单
                        Array(
                            'name'=>urlencode('香蕉'),
                            'type'=>'view',
                            'url'=>'https://baidu.com',
                        ),//第三个二级菜单
                    )
                ),//第二个一级菜单
                Array(
                    'name'=>urlencode('扫一扫'),
                    'type'=>'click',
                    'key'=>'erweima',
                ),//第三个一级菜单
            )
        );
        $postjson=urldecode(json_encode($postarr));
        //var_dump($this->curl($url,$postjson));
       return  json_decode($this->curl($url,$postjson),true);
    }
    //获取菜单
    function getItem(){
        $url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->accessToken;
        //var_dump($this->curl($url));
        return json_decode($this->curl($url),true);
    }
    //删除菜单栏
    function delItem(){
       $url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->accessToken;
        //var_dump($this->curl($url));
        return json_decode($this->curl($url),true);
    }
    //上传素材图片 获取url与media_id
    function  uploadImg(){
        $url="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={$this->accessToken}";
        $filepath=__DIR__."/img/86.jpg";
        $data=array("media"=>"@".$filepath);
        $rs=json_decode($this->curl($url,$data),true);
        return  $rs['url'];
    }
    //上传临时素材 返回（type ,media_id,createdtime）
    function  upload(){
        $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$this->accessToken}&type=image";
        $filepath=__DIR__."/img/86.jpg";
        $data=array("media"=>"@".$filepath);
        $rs=json_decode($this->curl($url,$data),true);
       // var_dump($rs);die;
        return  $rs['media_id'];
    }
    //获取临时素材
    function getmedia(){
        $mediaid=$this->upload();
        $url="https://api.weixin.qq.com/cgi-bin/media/get?access_token={$this->accessToken}&media_id={$mediaid}";
        //echo $url;
        $img = $this->curl($url);
        file_put_contents('1.gif',$img);
        echo '<img src="1.gif">';
      //return  var_dump($this->curl($url));
    }
    //上传永久图文素材
    function addNews(){
        $url="https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={$this->accessToken}";
        $rs=$this->addMaterial();//每次都在变
       $mediaid=$rs['media_id'];
        //$imgurl=$rs['url'];
        echo $mediaid;
        $data='{
            "articles":[{
                "author":"撒1",
                "content":"21212",
                "content_source_url":"",
                "digest":"Happy Day",
                "show_cover_pic":1,
                "thumb_media_id":"zxnXT1mw9c-APVgioZtQxh5wqK7WR_cpOkSoVMArdS8",
                "title":"Happy Day"
            }]

}'; echo $data;
        $rs=json_decode($this->curl($url,$data),true);
        var_dump($rs);
        return $rs['media_id'];
    }
    //上传素材  根据type不同上传的素材类型不同
    function addMaterial(){
        $url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$this->accessToken}&type=thumb";
        $filepath=__DIR__."/img/86.jpg";
        $data=array("media"=>"@".$filepath);
        $rs=json_decode($this->curl($url,$data),true);
         //var_dump($rs);die;
        return  $rs;
    }
    //用户管理
    //创建用户标签
    /*
     * $tag 标签名
     * */
    function createTag($name){
      $url="https://api.weixin.qq.com/cgi-bin/tags/create?access_token=".$this->accessToken;
       /* $data="{
              'tag':
                      {
                      'name' :'钻石会员'
                      },

            }";*/
        //json 里的属性只能用双引号，不能传参 改用数组形式，用数组时注意中文的转码
          $data=array(
              'tag'=>array(
                  'name'=>urlencode($name)
              )
          );
        $data=urldecode(json_encode($data));
        //echo $data;
        $rs= json_decode($this->curl($url,$data),true);
        return var_dump($rs);
    }
   //获取标签
    function getTag(){
        $url="https://api.weixin.qq.com/cgi-bin/tags/get?access_token=".$this->accessToken;
        $rs=json_decode($this->curl($url),true);
        return var_dump($rs);
    }
    //修改标签
    function  updateTag($id,$name){
        $url="https://api.weixin.qq.com/cgi-bin/tags/update?access_token=".$this->accessToken;
      /*  $data="{
               'tag' : {
                       'id': {$id},
                        'name' : '{$name}'
                       }
              }";*/
        $data=array(
            'tag'=>array(
                'name'=>urlencode($name),
                'id'=>$id
            )
        );
        $data=urldecode(json_encode($data));
        $rs=json_decode($this->curl($url,$data),true);
        var_dump($rs);
        if($rs['errcode']==0){
            echo '修改成功';
        }else{
            echo '修改失败';
        }
    }
    //删除标签
    function delTag($id){
        $url="https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=".$this->accessToken;
        $data=array(
            'tag'=>array(
                'id'=>$id
            )
        );
        $data=json_encode($data);
        $rs=json_decode($this->curl($url,$data),true);
        var_dump($rs);
        if($rs['errcode']==0){
            echo '删除成功';
        }else{
            echo '删除失败';
        }
    }
    //获取标签下的粉丝列表
    function getTagList($id,$openid=''){
        $url="https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=".$this->accessToken;
        $data=array(
                'tagid'=>$id,
                'next_openid'=>$openid
        );
        $data=json_encode($data);
        $rs=json_decode($this->curl($url,$data),true);
        var_dump($rs);
    }
    //为用户打标签
    /*
     * $id 标签ID
     * $arr 粉丝openid(数组)
     * */
    function addTag($id,$arr){
        $url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=".$this->accessToken;
        $data=array(
            'openid_list'=>$arr,
            'tagid'=>$id,
        );
        $data=json_encode($data);
        $rs=json_decode($this->curl($url,$data),true);
        if($rs['errcode']==0){
            echo '标签添加成功';
        }else{
            echo '标签添加失败';
        }
    }
    //为用户移除标签
    function removeTag($id,$arr){
         $url="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=".$this->accessToken;
        $data=array(
            'openid_list'=>$arr,
            'tagid'=>$id,
        );
        $data=json_encode($data);
        $rs=json_decode($this->curl($url,$data),true);
        if($rs['errcode']==0){
            echo '标签移除成功';
        }else{
            echo '标签移除失败';
        }
    }
    //获取用户的所有标签
    function getUserTag($arr){
      $url="https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=".$this->accessToken;
       $data=array( 'openid'=>$arr);
        $data=json_encode($data);
        $rs=json_decode($this->curl($url,$data),true);
      return var_dump($rs);
    }

}